package com.orange.delivery.presentation.common;

import java.util.Locale;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.StatelessLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.ResourceModel;
import org.springframework.security.core.userdetails.User;

import com.orange.delivery.presentation.WicketSession;
import com.orange.delivery.presentation.page.LogoutPage;

/**
 * The application header contains these informations
 * <ul>
 * <li>user logged in</li>
 * <li>logout link</li>
 * <li>language selection links</li>
 * </ul>
 * 
 */

public class HeaderPanel extends Panel {
	private static BookmarkablePageLink<Void> linkLogout;
	private static final long serialVersionUID = 4245911374449559174L;

	/**
	 * Create {@link HeaderPanel} containing logo, title and useful general links
	 */
	public HeaderPanel(String id) {
		super(id);
		createUserLabel();
		createLocaleLink();
		createLogoutLink();
	}

	private void createLogoutLink() {
		linkLogout = new BookmarkablePageLink<Void>("logoutLink", LogoutPage.class);
		linkLogout.add(new AttributeModifier("onclick", "return confirm('"
				+ (new ResourceModel("logout.confirm").getObject().toString()).replace("'", "\\'") + "');"));
		add(linkLogout);
	}

	private void createLocaleLink() {
		add(new LocaleLink("switchLang", getSession().getLocale()));
	}

	private void createUserLabel() {
		User user = WicketSession.get().getUser();
		String username;
		// If not already connected, user is null
		if (user != null) {
			username = user.getUsername();
		} else {
			// username should not be null to avoid NPE when rendering
			username = "";
		}
		Label userLabel = new Label("userId", username);
		add(userLabel);
	}

	/**
	 * Define link for switching locale.
	 * 
	 */
	private static class LocaleLink extends StatelessLink<Void> {
		private static final long serialVersionUID = 1L;

		public LocaleLink(String id, Locale locale) {
			super(id);
			getSession().setLocale(locale);
		}

		@Override
		public void onClick() {

			if ("fr".equals(getSession().getLocale().getLanguage())) {
				getSession().setLocale(Locale.US);
			} else {
				getSession().setLocale(Locale.FRANCE);
			}

			setResponsePage(this.getPage());
		}
	}
}